package com.micai.springboot.web;

import com.micai.springboot.entity.BookEntity;
import com.micai.springboot.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.Iterator;
import java.util.List;

/**
 * 描述：
 * <p>
 * Author: 赵新国
 * Date: 2018/1/23 16:58
 */
@RestController
public class BookController {

    private static final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookService bookService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /*@ModelAttribute
    public void before() {
        elasticsearchTemplate.deleteIndex(BookEntity.class);
        elasticsearchTemplate.createIndex(BookEntity.class);
        elasticsearchTemplate.putMapping(BookEntity.class);
        elasticsearchTemplate.refresh(BookEntity.class);
    }*/

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ResponseEntity save(@RequestBody BookEntity bookEntity) {
        bookService.save(bookEntity);
        return ResponseEntity.ok(bookEntity);
    }

    @RequestMapping(value = "/findOne/{id}", method = RequestMethod.GET)
    public BookEntity findOne(@PathVariable String id) {
        BookEntity bookEntity = bookService.findOne(id);
        return bookEntity;
    }

    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public void findAll() {
        Iterable<BookEntity> bookEntities = bookService.findAll();
        Iterator<BookEntity> iterator = bookEntities.iterator();
        while (iterator.hasNext()) {
            BookEntity bookEntity = iterator.next();
            logger.info("bookEntity: {}", bookEntity);
        }
    }

    @RequestMapping(value = "/findByTitle/{title}", method = RequestMethod.GET)
    public List<BookEntity> findByTitle(@PathVariable String title) {
        List<BookEntity> bookEntities = bookService.findByTitle(title);
        return bookEntities;
    }

    @RequestMapping(value = "/findByAuthor/{title}", method = RequestMethod.GET)
    public Page<BookEntity> findByAuthor(@PathVariable String title) {
        Page<BookEntity> bookEntityPage = bookService.findByAuthor(title, new PageRequest(0, 10));
        return bookEntityPage;
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteById(@PathVariable String id) {
        BookEntity bookEntity = bookService.findOne(id);
        if (bookEntity != null) {
            bookService.delete(bookEntity);
        }
        return ResponseEntity.ok(200);
    }

}
